package com.meizhuang.controller;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.meizhuang.ShoppingCartExt;
import com.meizhuang.base.BaseController;
import com.meizhuang.entity.*;
import com.meizhuang.mapper.base.BaseWrapper;
import com.meizhuang.result.JsonResult;
import com.meizhuang.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.stream.Collectors;

@RestController
@Api(tags = "我的关注与粉丝及点赞API")
public class FollowController extends BaseController {


    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private FollowService followService;

    @Autowired
    private OfferProductService offerProductService;

    @Autowired
    private OfferProductLikeService offerProductLikeService;

    @Autowired
    private ShopService shopService;
    /**
     * 添加关注
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/follow_add")
    @ApiOperation(value = "添加关注", notes = "添加关注")
    public JsonResult shop_add(HttpServletRequest request, HttpServletResponse response){

        Map<String,Object> retMap = new HashMap<>();

        Integer userSession = (Integer)super.getSession().getAttribute(UserInfo.USER_SESSION_UID);

        if(userSession == null){
            retMap.put("msg", "请登录");
            return JsonResult.buildError(retMap);
        }

        String followUid = request.getParameter("follow_uid");

        if(StringUtils.isBlank(followUid)) {
            retMap.put("msg", "无效商家");
            return JsonResult.buildError(retMap);
        }

        EntityWrapper<UserInfo> userInfoWrapper = new EntityWrapper();
        userInfoWrapper.eq("uid", followUid);
        UserInfo userInfo = userInfoService.selectOne(userInfoWrapper);

        if( null == userInfo){
            retMap.put("msg", "关注了无效商户");
            return JsonResult.buildError(retMap);
        }
        Lock lock = new ReentrantLock();
        try {
            lock.lock();

            EntityWrapper<Follow> followEntityWrapper = new EntityWrapper();
            followEntityWrapper.eq("follow_uid",followUid);
            followEntityWrapper.eq("uid",userSession);
            Follow follow = followService.selectOne(followEntityWrapper);

            if(null != follow) {
                retMap.put("msg", "已关注");
                return JsonResult.buildError(retMap);
            }
            follow = new Follow();
            follow.setCtime(new Date());
            follow.setUid(userSession);
            follow.setFollowUid(Integer.parseInt(followUid));
            follow.setLogoImg(userInfo.getLogoImg());
            follow.setMtime(follow.getCtime());
            follow.setStoreName(userInfo.getStoreName());
            follow.setStoreRemark(userInfo.getStoreRemark());
            follow.setTradeStall(userInfo.getTradeStall());

            followService.insert(follow);

        }catch (Exception e){
            retMap.put("msg", e.getMessage());
            return JsonResult.buildError(retMap);
        }finally {
            lock.unlock();
        }

        return JsonResult.buildSuccess(retMap);
    }


    /**
     * 取消关注/取消粉丝
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/follow_delete")
    @ApiOperation(value = "取消关注/取消粉丝", notes = "取消关注/取消粉丝")
    public JsonResult follow_delete(HttpServletRequest request, HttpServletResponse response){

        Map<String,Object> retMap = new HashMap<>();

        Integer userSession = (Integer)super.getSession().getAttribute(UserInfo.USER_SESSION_UID);

        if(userSession == null){
            retMap.put("msg", "请登录");
            return JsonResult.buildError(retMap);
        }

        String followUid = request.getParameter("follow_uid");

        if(StringUtils.isBlank(followUid)) {
            retMap.put("msg", "商户follow_uid不能为空");
            return JsonResult.buildError(retMap);
        }

        EntityWrapper<UserInfo> userInfoWrapper = new EntityWrapper();
        userInfoWrapper.eq("uid", followUid);
        UserInfo userInfo = userInfoService.selectOne(userInfoWrapper);

        if( null == userInfo){
            retMap.put("msg", "无效的商户");
            return JsonResult.buildError(retMap);
        }
        Lock lock = new ReentrantLock();
        try {
            lock.lock();

            EntityWrapper<Follow> followEntityWrapper = new EntityWrapper();
            followEntityWrapper.eq("follow_uid",followUid);
            followEntityWrapper.eq("uid",userSession);
            Follow follow = followService.selectOne(followEntityWrapper);

            if(null == follow) {
                retMap.put("msg", "已取消关注");
                return JsonResult.buildError(retMap);
            }


            followService.deleteById(follow.getId());

        }catch (Exception e){
            retMap.put("msg", e.getMessage());
            return JsonResult.buildError(retMap);
        }finally {
            lock.unlock();
        }

        return JsonResult.buildSuccess(retMap);
    }

    /**
     * 我的关注
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/follow_list")
    @ApiOperation(value = "我的关注列表", notes = "我的关注列表")
    public JsonResult follow_list(HttpServletRequest request, HttpServletResponse response){

        Map<String,Object> retMap = new HashMap<>();

        Integer userSession = (Integer)super.getSession().getAttribute(UserInfo.USER_SESSION_UID);

        if(userSession == null){
            retMap.put("msg", "请登录");
            return JsonResult.buildError(retMap);
        }
        EntityWrapper<Follow> followEntityWrapper = new EntityWrapper();
        followEntityWrapper.eq("uid", userSession);
        List<Follow> follows = followService.selectList(followEntityWrapper);
        retMap.put("follows",follows);

        if(CollectionUtils.isEmpty(follows)){
            return JsonResult.buildSuccess(retMap);
        }

        //查询商家
        EntityWrapper<UserInfo> userInfoWrapper = new EntityWrapper();
        userInfoWrapper.in("uid", follows.stream().map(m -> m.getFollowUid()).collect(Collectors.toList()));
        List<UserInfo> userInfoList = userInfoService.selectList(userInfoWrapper);

        follows.stream().forEach(item->{
            userInfoList.stream().filter(f->f.getUid().intValue() == item.getFollowUid().intValue()).findFirst().ifPresent(p->{
                item.setGate(p.getUid());
                item.setRandom(p.getRandom());
            });
        });
        return JsonResult.buildSuccess(retMap);
    }


    /**
     * 我的粉丝
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/fans_list")
    @ApiOperation(value = "我的粉丝列表", notes = "我的粉丝列表")
    public JsonResult fans_list(HttpServletRequest request, HttpServletResponse response){

        Map<String,Object> retMap = new HashMap<>();


        Integer userSession = (Integer)super.getSession().getAttribute(UserInfo.USER_SESSION_UID);

        if(userSession == null){
            retMap.put("msg", "请登录");
            return JsonResult.buildError(retMap);
        }

        String uid = request.getParameter("uid");

        if(StringUtils.isNotBlank(uid)) {
            userSession = Integer.valueOf(uid);
        }

        EntityWrapper<Follow> followEntityWrapper = new EntityWrapper();
        followEntityWrapper.eq("follow_uid", userSession);
        List<Follow> follows = followService.selectList(followEntityWrapper);

        List<UserInfo> userInfoList = new ArrayList<>();
        //查询商家
        if(!CollectionUtils.isEmpty(follows)){
            EntityWrapper<UserInfo> userInfoWrapper = new EntityWrapper();
            userInfoWrapper.in("uid", follows.stream().map(m -> m.getUid()).collect(Collectors.toList()));
            userInfoList = userInfoService.selectList(userInfoWrapper);
        }
        retMap.put("follows",userInfoList);
        return JsonResult.buildSuccess(retMap);
    }


    /**
     * 我关注的商户报价
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/follow_list_product")
    @ApiOperation(value = "我关注的商户报价", notes = "我关注的商户报价")
    public JsonResult follow_list_product(HttpServletRequest request, HttpServletResponse response){

        Map<String,Object> retMap = new LinkedHashMap<>();

        Integer userSession = (Integer)super.getSession().getAttribute(UserInfo.USER_SESSION_UID);

        if(userSession == null){
            retMap.put("msg", "请登录");
            return JsonResult.buildError(retMap);
        }

        EntityWrapper<Follow> followEntityWrapper = new EntityWrapper();
        followEntityWrapper.eq("uid", userSession);
        List<Follow> follows = followService.selectList(followEntityWrapper);

        if(CollectionUtils.isEmpty(follows)){
            return JsonResult.buildSuccess(retMap);
        }

        List<Integer> collect = follows.stream().map(m -> m.getFollowUid()).collect(Collectors.toList());

//        final long days = 150;
//        EntityWrapper<OfferProduct> offerWrapper = new EntityWrapper<OfferProduct>();
//        offerWrapper.in("uid", collect);
//        Date now = new Date();
//        offerWrapper.ge("ctime", new Date(now.getTime() - days * 24 * 60 * 60 * 1000));//最近15天报价
//        offerWrapper.orderBy("ctime", false);
//
//        List<OfferProduct> offerProducts = offerProductService.selectList(offerWrapper);
//
//        Map<Integer, List<OfferProduct>> uIdMap = offerProducts.stream().collect(Collectors.groupingBy(OfferProduct::getUid));
//        Iterator<Map.Entry<Integer, List<OfferProduct>>> iterator = uIdMap.entrySet().iterator();
//        while(iterator.hasNext()){
//            Map.Entry<Integer, List<OfferProduct>> entry = iterator.next();
//
//            Integer uId = entry.getKey();
//            List<OfferProduct> products = entry.getValue();
//
//            Map<String,Object>  map = new LinkedHashMap<>();
//
//            EntityWrapper<UserInfo> userInfoWrapper = new EntityWrapper();
//            userInfoWrapper.eq("uid", uId);
//            UserInfo userInfo = userInfoService.selectOne(userInfoWrapper);
//            if(null == userInfo) {
//                continue;
//            }
//            map.put("storeName",userInfo.getStoreName());
//            map.put(String.valueOf(uId),userInfo.getUid());
//            for(long i=0;i<=days;i++){
//
//                final int index = (int) i;
//                products.stream().filter(f -> index == (now.getTime() - f.getCtime().getTime()) / 1000 / 3600 / 24).map(m->m.getCtime()).findFirst().ifPresent(p->{
//                    long count = products.stream().filter(f -> index == (now.getTime() - f.getCtime().getTime()) / 1000 / 3600 / 24).count();
//                    map.put("count",count);
//                    map.put("date",p);
//                    retMap.put(String.valueOf(uId),map);
//                });
//            }
//        }

        /*************************************************/
        collect.add(userSession);
        BaseWrapper<UserInfo> wrapper = new BaseWrapper<UserInfo>(UserInfo.selectFiled, UserInfo.fromFiled);

        wrapper.isNotNull("product_update_time")
                .groupBy("o.ctime").orderBy("product_update_time", false);
        wrapper.in("u.uid",collect);
        wrapper.last("limit 200");

        List<UserInfo> list = userInfoService.selectByList(wrapper);

        for(UserInfo userInfo : list){

            String fromDate = DateUtil.format(userInfo.getProductUpdateTime(), DatePattern.NORM_DATETIME_PATTERN);
            userInfo.setSctime(fromDate);

        }
        list.forEach(item->{
            Map<String,Object>  map = new LinkedHashMap<>();
            map.put("count",item.getCount());
            map.put("date",item.getProductUpdateTime());
            map.put("storeName",item.getStoreName());
            map.put("gate",item.getUid());
            map.put("random",item.getRandom());

            retMap.put(String.valueOf(item.getUid()),map);
        });
        /*************************************************/
        return JsonResult.buildSuccess(retMap);
    }


    /**
     * 点赞商品
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/like")
    @ApiOperation(value = "点赞商品", notes = "点赞商品")
    public JsonResult like(HttpServletRequest request, HttpServletResponse response){

        Integer userSession = (Integer)super.getSession().getAttribute(UserInfo.USER_SESSION_UID);
        Map<String,Object> retMap = new LinkedHashMap<>();

        if(userSession == null){
            retMap.put("msg", "请登录");
            return JsonResult.buildError(retMap);
        }

        String offerProductId = request.getParameter("offer_product_id");

        if(StringUtils.isBlank(offerProductId)){
            retMap.put("msg", "商品id不能为空,offer_product里面找id填写参数");
            return JsonResult.buildError(retMap);
        }

        EntityWrapper<OfferProduct> offerProductEntityWrapper = new EntityWrapper();
        offerProductEntityWrapper.eq("id",offerProductId);
        OfferProduct offerProduct = offerProductService.selectOne(offerProductEntityWrapper);

        if(null == offerProduct) {
            retMap.put("msg", "商品id不存在,offer_product找一个存在的id");
            return JsonResult.buildError(retMap);
        }

        Lock lock = new ReentrantLock();
        try {
            lock.lock();
            EntityWrapper<OfferProductLike> offerProductLikeEntityWrapper = new EntityWrapper();
            offerProductLikeEntityWrapper.eq("uid", userSession);
            offerProductLikeEntityWrapper.eq("offer_product_id",offerProductId);

            OfferProductLike offerProductLike = offerProductLikeService.selectOne(offerProductLikeEntityWrapper);

            if(null != offerProductLike ){
                retMap.put("msg", "该商品已点赞");
                return JsonResult.buildError(retMap);
            }

            offerProductLike = new OfferProductLike();
            offerProductLike.setCreateTime(new Date());
            offerProductLike.setOfferProductId(offerProduct.getId());
            offerProductLike.setOfferProduct(offerProduct.getOfferProduct());
            offerProductLike.setUid(userSession);
            offerProductLike.setUpdateTime(offerProductLike.getCreateTime());
            offerProductLike.setProduct(offerProduct.getProduct());
            offerProductLikeService.insert(offerProductLike);
        }catch (Exception e){
            retMap.put("msg", e.getMessage());
            return JsonResult.buildError(retMap);
        }finally {
            lock.unlock();
        }
        return JsonResult.buildSuccess(retMap);
    }

    /**
     * 点赞列表
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/like_list")
    @ApiOperation(value = "我的点赞列表", notes = "我的点赞列表")
    public JsonResult likeList(HttpServletRequest request, HttpServletResponse response){

        Map<String,Object> retMap = new LinkedHashMap<>();

        Integer userSession = (Integer)super.getSession().getAttribute(UserInfo.USER_SESSION_UID);

        if(userSession == null){
            retMap.put("msg", "请登录");
            return JsonResult.buildError(retMap);
        }

        String uid = request.getParameter("uid");

        if(StringUtils.isNotBlank(uid)) {
            userSession = Integer.valueOf(uid);
        }

        EntityWrapper<OfferProductLike> offerProductLikeEntityWrapper = new EntityWrapper();
        offerProductLikeEntityWrapper.eq("uid", userSession);

        List<OfferProductLike> offerProductLikes = offerProductLikeService.selectList(offerProductLikeEntityWrapper);

        List<OfferProductLikeExt> collect = offerProductLikes.stream().map(m -> {
            OfferProductLikeExt offerProductLikeExt = new OfferProductLikeExt(m);

            EntityWrapper<OfferProduct> offerProductEntityWrapper = new EntityWrapper();
            offerProductEntityWrapper.eq("id", m.getOfferProductId());
            OfferProduct offerProduct = offerProductService.selectOne(offerProductEntityWrapper);

            if (null != offerProduct) {

                EntityWrapper<UserInfo> userInfoWrapper = new EntityWrapper();
                userInfoWrapper.in("uid", offerProduct.getUid());
                UserInfo userInfo = userInfoService.selectOne(userInfoWrapper);

                if (null != userInfo) {
                    offerProductLikeExt.setStoreName(userInfo.getStoreName());
                }
            }
            return offerProductLikeExt;
        }).collect(Collectors.toList());

        retMap.put("offerProductLikes",collect);

        return JsonResult.buildSuccess(retMap);
    }


    /**
     * 取消点赞商品
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/like_delete")
    @ApiOperation(value = "取消点赞商品", notes = "取消点赞商品")
    public JsonResult like_delete(HttpServletRequest request, HttpServletResponse response){

        Integer userSession = (Integer)super.getSession().getAttribute(UserInfo.USER_SESSION_UID);
        Map<String,Object> retMap = new LinkedHashMap<>();

        if(userSession == null){
            retMap.put("msg", "请登录");
            return JsonResult.buildError(retMap);
        }

        String offerProductId = request.getParameter("offer_product_id");

        if(StringUtils.isBlank(offerProductId)){
            retMap.put("msg", "商品id不能为空,offer_product里面找id填写参数");
            return JsonResult.buildError(retMap);
        }

        Lock lock = new ReentrantLock();
        try {
            lock.lock();
            EntityWrapper<OfferProductLike> offerProductLikeEntityWrapper = new EntityWrapper();
            offerProductLikeEntityWrapper.eq("uid", userSession);
            offerProductLikeEntityWrapper.eq("offer_product_id",offerProductId);

            OfferProductLike offerProductLike = offerProductLikeService.selectOne(offerProductLikeEntityWrapper);

            if(null != offerProductLike ){
                offerProductLikeService.deleteById(offerProductLike.getId());
                return JsonResult.buildSuccess(retMap);
            }

            EntityWrapper<ShoppingCart> shoppingCartEntityWrapper = new EntityWrapper();
            shoppingCartEntityWrapper.eq("offset_product_id",offerProductId);
            shoppingCartEntityWrapper.eq("uid",userSession);
            shoppingCartEntityWrapper.eq("store",1);
            ShoppingCart shoppingCart = shopService.selectOne(shoppingCartEntityWrapper);

            if(null !=shoppingCart ){
                shopService.deleteById(shoppingCart.getId());
                return JsonResult.buildSuccess(retMap);
            }

        }catch (Exception e){
            retMap.put("msg", e.getMessage());
            return JsonResult.buildError(retMap);
        }finally {
            lock.unlock();
        }
        return JsonResult.buildSuccess(retMap);
    }
}
